package ink.lovejinhu.leetcode;

import ink.lovejinhu.common.ListNode;

/**
 * @author jinhu
 * created 2021-07-02 14:55
 */
public class Solution_0002 {
    /**
     * 给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
     * 大数的存储上都是地位存在索引低的地方
     *
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        /**
         * 以l1为结果链
         */
        int jinwei = 0;
        ListNode head = l1;
        ListNode preL1 = null;
        while (l1 != null && l2 != null) {
            int i = l1.val + l2.val + jinwei;
            jinwei = i / 10;
            i = i % 10;
            l1.val = i;
            preL1 = l1;
            l1 = l1.next;
            l2 = l2.next;
        }
        if (l1 == null && l2 == null) {
            if (jinwei != 0) {
                preL1.next = new ListNode(jinwei);
                preL1.next.next = null;
            }
        }
        if (l1 != null) {   //l1不为空
            ListNode preL11 = null;
            while (l1 != null) {
                int i = l1.val + jinwei;
                jinwei = i / 10;
                i = i % 10;
                l1.val = i;
                preL11 = l1;
                preL1=preL1.next;
                l1 = l1.next;
            }
            if (jinwei != 0) {
                preL11.next = new ListNode(jinwei);
                preL11.next.next = null;
            }

        }
        if (l2 != null) {   //l2不为空
            ListNode preL11 = null;
            while (l2 != null) {
                int i = l2.val + jinwei;
                jinwei = i / 10;
                i = i % 10;
                l2.val = i;
                preL1.next = l2;
                preL1=preL1.next;
                preL11 = l2;
                l2 = l2.next;
            }
            if (jinwei != 0) {
                preL11.next = new ListNode(jinwei);
                preL11.next.next = null;
            }
        }

        return head;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(7);
        l1.next.next = new ListNode(8);
        ListNode l2 = new ListNode(0);
       new Solution_0002().addTwoNumbers(l2, l1);
    }
}
